package de.mauandmau;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

import android.util.Log;

public class Server implements Runnable {

	ServerSocket server;
	Socket connection;
	
	boolean alive = true;

	BufferedInputStream bis;
	BufferedOutputStream bos;

	byte[] receivedData;
	int in;
	ArrayList<BufferedOutputStream> bosClients = new ArrayList<BufferedOutputStream>();

	public void pushToAllClients(String command) {
		command += "\n";
		for (BufferedOutputStream bos : bosClients) {
			try {
				bos.write(command.getBytes("UTF-8"));
				bos.flush();
			} catch (Exception e) {
				Log.e(Utils.TAG, "fehler beim Senden", e);
			}
		}
	}

	public void pushToClient(int index, String command) {
		command += "\n";
		BufferedOutputStream bos = bosClients.get(index);
		try {
			bos.write(command.getBytes("UTF-8"));
			bos.flush();
		} catch (Exception e) {
			Log.e(Utils.TAG, "fehler beim Senden", e);
		}
	}

	/**
	 * Deals some card to the users
	 */
	public void sendRandomCardToAllClients() {
		new Thread() {
			public void run() {
				try {
					sleep(20);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				int rand = (int) (Math.random() * 50);
				pushToAllClients("" + rand);
			}
		}.start();
	}

	public void run() {
		try {
			alive = true;
			server = new ServerSocket(4444);
			Log.d("TCP..", "started...");

			while (alive) {
				connection = server.accept();
				Log.w(Utils.TAG, "client connected - state 1");
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							receivedData = new byte[8192];
							Log.d(Utils.TAG, "client connected");
							bos = new BufferedOutputStream(connection
									.getOutputStream());
							bosClients.add(bos);
							InputStream is = connection.getInputStream();
							BufferedReader br = new BufferedReader(
									new InputStreamReader(is));
							Log.d("hello:", "client i/o streams connected");
							String line = null;
							while ((line = br.readLine()) != null) {
								handleCommandFromClient(line);
							}
							Log.w(Utils.TAG, "client disocnnected");
							bos.close();
						} catch (IOException e) {
							Log.e(Utils.TAG, "error", e);
						}
					}

					protected void handleCommandFromClient(String string) {
						Log.w(Utils.TAG, "command from client" + string);
						pushToAllClients("this is from server" + string); // wieder
						// zurücksenden
					}
				});
				thread.start();
			}
		} catch (Exception e) {
			Log.e(Utils.TAG, "error", e);
		}
	}

	public void deleteAllCards() {
		pushToAllClients("Kill");
	}

	public void destroy() {
		try {
			alive = false;
			if (server != null) {
				server.close();
			}
			if (bos != null) {
				bos.close();
			}
			if (bis != null) {
				bis.close();
			}
			if (connection != null) {
				connection.close();
			}
			Log.w(Utils.TAG, "Server shutdown");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}